import os
import yaml
from loguru import logger
from utils.object_utils import cache


# 返回项目目录路径，或路径的文件名
def get_path(project_dir,file_path=None):
    r"""
    返回结果 ：E:\python_project\api_test_09\data\user_add_folw.yml
    :param project_dir: 相当于传递是data
    :param file_path: 相当于user_add_flow.yml
    :return:
    """
    project_path = os.path.dirname(os.path.dirname(__file__))
    path = os.path.join(project_path,project_dir)      # 就会把这两个路径给拼接起来
    if file_path is not None:
        path = os.path.join(path,file_path)
        return path
    return path


# 读取yaml文件，返回的是python格式
def read_yaml_file(yml_file):
    yml_path = get_path('data',yml_file)
    with open(yml_path,encoding='utf-8') as yml_obj:
        data = yaml.safe_load(yml_obj)
        logger.info("返回测试用例数据为:{}".format(data))
        return data


# 判断是否包括大括号 ：只要有大括号，代表要从缓存中提取，提取的健名就是大括号里面的名字
def is_contain_brace(value):
    """
    返回的是user_id的值
    :param value: {{user_id}}
    :return:
    """
    start_index = value.find("{{")
    end_index = value.find("}}")
    if start_index >=0 and end_index >=0:
        # 1. 从缓存中其它它的值
        vls = cache.get(value[start_index + 2:end_index])
        logger.debug("从缓存中提取的键名:{},值:{}".format(value[start_index+2:end_index],vls))
        return vls
    return value


if __name__ == '__main__':
    print(get_path('data'))
    print(read_yaml_file('user_add_flow.yml'))
    print(is_contain_brace("{{user_id}}"))
